package cn.exrick.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class ControllerUtils {
    public static ServletRequestAttributes getServletRequestAttributes() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes;
    }

    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        return getServletRequestAttributes().getRequest();
    }


    private ThreadLocal<String> body = new ThreadLocal<>();
    /**
     * 获取当前请求的请求体
     *
     * @return
     */
    public String getBody() {
        if (body.get() == null) {
            try {
                InputStream in = getRequest().getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                StringBuffer buffer = new StringBuffer();
                String line = " ";
                while ((line = reader.readLine()) != null){
                    buffer.append(line);
                }
                body.set(buffer.toString());
                return body.get();
            } catch (Exception e) {
                return "";
            }
        } else {
            return body.get();
        }

    }
}
